// uecgi_filelog.cpp
#include <windows.h>
#include <tchar.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <share.h>

extern "C" int enable_stdout;
extern "C" int enable_stderr;

// API declaration
#include "uecgi_filelog.h"

int InitCGILogFile(const _TCHAR* strLogFileName)
{
	_TCHAR strModuleFilePath[MAX_PATH + 1];
	_TCHAR strLogFilePath[MAX_PATH + 15];
	int fd = 0;

	// disable stderr and stdout
	enable_stdout = 0;
	enable_stderr = 0;

	if (GetModuleFileName(NULL, strModuleFilePath, MAX_PATH))
	{
		_TCHAR* pos = _tcsrchr(strModuleFilePath, _T('\\'));
		if (pos)
		{
			_tcsncpy_s(strLogFilePath, MAX_PATH + 14, strModuleFilePath, (int)(pos - strModuleFilePath + 1));
		}
		else
		{
			strLogFilePath[0] = 0;
		}
		
		_tcscat_s(strLogFilePath, MAX_PATH + 14, _T("..\\..\\logs\\"));
		if (strLogFileName == NULL || _tcslen(strLogFileName) == 0)
		{
			pos++;
			_tcscat_s(strLogFilePath, MAX_PATH + 14, pos);
			_tcscat_s(strLogFilePath, MAX_PATH + 14, _T(".log"));
		}
		else
		{
			_tcscat_s(strLogFilePath, MAX_PATH + 14, strLogFileName);
		}

		_tsopen_s(&fd, strLogFilePath, _O_APPEND | _O_CREAT | _O_WRONLY, _SH_DENYNO, _S_IREAD | _S_IWRITE);
	}

	return fd;
}